package com.docMan.service.impl;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.docMan.dao.BaseDao;
import com.docMan.dao.pojo.DocDirectory;
import com.docMan.dao.pojo.DocDirectoryRange;
import com.docMan.dao.pojo.DocDirectoryRangeId;
import com.docMan.service.DocDirectoryRangeService;
import com.docMan.utils.FinalConfig;

@Service("docDirectoryRangeService")
public class DocDirectoryRangeServiceImpl extends
		BaseServiceImpl<DocDirectoryRange> implements DocDirectoryRangeService {

	private HttpSession session;

	@Autowired
	public void setSession(HttpSession session) {
		this.session = session;
	}

	@Resource
	@Override
	public void setDao(BaseDao<DocDirectoryRange> dao) {
		// TODO Auto-generated method stub
		super.setDao(dao);
	}

	@Override
	public boolean canHumanSeeDir(int directoryId, int humanId) {
		List<DocDirectoryRange> docDirectoryRanges = find(
				"select d from DocDirectoryRange d where d.id.directoryId=?",
				directoryId);
		for (DocDirectoryRange docDirectoryRange : docDirectoryRanges) {
			if (docDirectoryRange.getId().getHumanId().equals(humanId)) {
				return true;
			}
		}
		return false;
	}

	@Override
	public void saveDirSeeableHuman(int docDirectoryId, String displayRange,
			List<Integer> humanIds) {
		if (displayRange.equals(FinalConfig.DirectoryDisplayRange_HUMANS)) {
			Set<Integer> humansSet = new HashSet<>();
			saveDirectoryAuthor(docDirectoryId,
					(int) session.getAttribute(FinalConfig.SESSION_HUMANID));
			humansSet.add((int) session
					.getAttribute(FinalConfig.SESSION_HUMANID));
			for (Integer integer : humanIds) {
				if (!humansSet.contains(integer)) {
					DocDirectoryRange docDirectoryRange = new DocDirectoryRange(
							new DocDirectoryRangeId(docDirectoryId, integer));
					save(docDirectoryRange);
				} else {
					humansSet.add(integer);
				}
			}
		}
	}

	private void saveDirectoryAuthor(int docDirectoryId, int humanId) {
		DocDirectoryRange docRange = new DocDirectoryRange(
				new DocDirectoryRangeId(docDirectoryId, humanId));
		save(docRange);
	}
}
